<template>
<div class="dropdown" ref="dropdownRef">
  <a type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false" @click.prevent="toggleOpen">
    {{title}}
  </a>
  <ul class="dropdown-menu" v-if="isShow" style="display:block;">
    <slot></slot>
  </ul>
  </div>
</template>

<script lang='ts'>
import { defineComponent, watch, ref } from 'vue'
import userClickOutside from '../hooks/userClickOutside'
export default defineComponent({
  name: 'DropDown',
  props: {
    title: {
      type: String,
      require: true
    }
  },
  setup () {
    const isShow = ref(false)
    const dropdownRef = ref<null | HTMLElement>(null)
    const toggleOpen = () => {
      isShow.value = !isShow.value
    }
    const isOutSide = userClickOutside(dropdownRef)
    watch(isOutSide, () => {
      if (isShow.value && isOutSide.value) {
        isShow.value = false
      }
    })
    // const handle = (e: MouseEvent) => {
    //   if (dropdownRef.value) {
    //     if (!dropdownRef.value.contains(e.target as HTMLElement) && isShow.value) {
    //       isShow.value = false
    //     }
    //   }
    // }
    // onMounted(() => {
    //   document.addEventListener('click', handle)
    // })
    // onUnmounted(() => {
    //   document.removeEventListener('click', handle)
    // })
    return {
      isShow,
      toggleOpen,
      dropdownRef
    }
  }
})
</script>

<style>

</style>
